// (function(window) {
//   function MyPromise(excutor) {
//     this.PromiseState = 'pending' // 保存Promise对象的状态，初始值为pending
//     this.PromiseResult = undefined // 存储promise对象结果数据的属性
//       // 主要用于存储先指定回调后改变状态的回调
//     this.PromiseCallbacks = [] // 存储Promise对象回调函数的数组，每个元素的格式{onResolved:xxx,onRejected:xxx}

//     const self = this

//     function resolve_(value) {
//       if (self.PromiseState !== 'pending') return // promise对象状态只能修改一次
//       self.PromiseState = 'fulfilled'
//       self.PromiseResult = value

//       setTimeout(() => {
//         self.PromiseCallbacks.forEach(callback => {
//           callback.onResolved()
//         })
//       })
//     }

//     function reject_(reason) {
//       if (self.PromiseState !== 'pending') return
//       self.PromiseState = 'rejected'
//       self.PromiseResult = reason

//       setTimeout(() => {
//         self.PromiseCallbacks.forEach(callback => {
//           callback.onRejected()
//         })
//       })
//     }

//     try {
//       excutor(resolve_, reject_)
//     } catch (e) {
//       console.log(e);
//       reject_(e)
//     }
//   }

//   MyPromise.prototype.then = function(onResolved, onRejected) {
//     /**
//      * Promise原型对象的then(),指定成功和失败的回调函数，返回一个Promise对象
//      * @onResolved 成功执行的回调
//      * @onRejected 失败执行的回调
//      */

//     // 设置异常穿透
//     if (typeof onRejected !== 'function') {
//       onRejected = (reason) => {
//         throw reason
//       }
//     }

//     // 设置值传递
//     if (typeof onResolved !== 'function') {
//       onResolved = value => value
//     }

//     return new MyPromise((resolve, reject) => {
//       let that = this

//       function callback(type) {
//         try {
//           let thenReturn = type(that.PromiseResult) // then中onResolved回调的返回值
//           if (thenReturn instanceof MyPromise) {
//             // 1.返回值为MyPromise对象,
//             thenReturn.then(value => {
//               resolve(value)
//             }, reason => {
//               reject(reason)
//             })
//           } else {
//             // 2.返回为常值,包装为Promis.resolve()
//             resolve(thenReturn)
//           }
//         } catch (e) {
//           return reject(e)
//         }
//       }
//       if (this.PromiseState === 'fulfilled') {
//         setTimeout(() => {
//           callback(onResolved)
//         })
//       } else if (this.PromiseState === 'rejected') {
//         setTimeout(() => {
//           callback(onRejected)
//         })
//       } else {
//         this.PromiseCallbacks.push({
//           onResolved() {
//             callback(onResolved)
//           },
//           onRejected() {
//             callback(onRejected)
//           }
//         })
//       }
//     })
//   }

//   MyPromise.prototype.catch = function(onRejected) {
//     /**
//      * Promise原型对象的catch(),指定失败的回调函数，返回一个Promise对象
//      * @onRejected 失败执行的回调
//      */
//     return this.then(undefined, onRejected)
//   }

//   MyPromise.resolve = function(value) {
//     /**
//      * Promise原型对象的resolve(),返回一个指定value的成功的Promise对象
//      */
//     return new MyPromise((resolve, reject) => {
//       if (value instanceof MyPromise) {
//         value.then(v => {
//           resolve(v)
//         }, r => {
//           reject(r)
//         })
//       } else {
//         resolve(value)
//       }
//     })
//   }

//   MyPromise.reject = function(reason) {
//     /**
//      * Promise原型对象的resolve(),返回一个指定reason的失败的Promise对象
//      */
//     return new MyPromise((undefined, reject) => {
//       reject(reason)
//     })
//   }

//   MyPromise.all = function(promises) {
//     /**
//      * Promise原型对象的all(),返回一个promise对象，只有promises数组种全部的promise对象都为成功，
//      * 才返回成功的promise对象，否则返回失败的promise对象
//      */
//     return new MyPromise((resolve, reject) => {
//       let promiseCount = 0 // 记录成功的个数
//       let promiseResults = [] // 记录成功的promise值
//       promises.forEach((promise, index) => {
//         promise.then(value => {
//           promiseResults[index] = value
//           if (++promiseCount === promises.length) resolve(promiseResults)
//         }, reason => {
//           reject(reason)
//         })
//       })
//     })
//   }

//   MyPromise.race = function(promises) {
//     /**
//      * Promise原型对象的race(),promises中率先确认状态的promise决定了返回的promise
//      */
//     return new MyPromise((resolve, reject) => {
//       promises.forEach(promise => {
//         promise.then(value => {
//           resolve(value)
//         }, reason => {
//           reject(reason)
//         })
//       })
//     })
//   }

//   window.MyPromise = MyPromise
// })(window)


class MyPromise {
  constructor(excutor) {
    this.PromiseState = 'pending' // 保存Promise对象的状态，初始值为pending
    this.PromiseResult = undefined // 存储promise对象结果数据的属性
      // 主要用于存储先指定回调后改变状态的回调
    this.PromiseCallbacks = [] // 存储Promise对象回调函数的数组，每个元素的格式{onResolved:xxx,onRejected:xxx}

    const self = this

    function resolve_(value) {
      if (self.PromiseState !== 'pending') return // promise对象状态只能修改一次
      self.PromiseState = 'fulfilled'
      self.PromiseResult = value

      setTimeout(() => {
        self.PromiseCallbacks.forEach(callback => {
          callback.onResolved()
        })
      })
    }

    function reject_(reason) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'rejected'
      self.PromiseResult = reason

      setTimeout(() => {
        self.PromiseCallbacks.forEach(callback => {
          callback.onRejected()
        })
      })
    }

    try {
      excutor(resolve_, reject_)
    } catch (e) {
      console.log(e);
      reject_(e)
    }
  }

  then(onResolved, onRejected) {

    // 设置异常穿透
    if (typeof onRejected !== 'function') {
      onRejected = (reason) => {
        throw reason
      }
    }

    // 设置值传递
    if (typeof onResolved !== 'function') {
      onResolved = value => value
    }

    return new MyPromise((resolve, reject) => {
      let that = this

      function callback(type) {
        try {
          let thenReturn = type(that.PromiseResult) // then中onResolved回调的返回值
          if (thenReturn instanceof MyPromise) {
            // 1.返回值为MyPromise对象,
            thenReturn.then(value => {
              resolve(value)
            }, reason => {
              reject(reason)
            })
          } else {
            // 2.返回为常值,包装为Promis.resolve()
            resolve(thenReturn)
          }
        } catch (e) {
          return reject(e)
        }
      }
      if (this.PromiseState === 'fulfilled') {
        setTimeout(() => {
          callback(onResolved)
        })
      } else if (this.PromiseState === 'rejected') {
        setTimeout(() => {
          callback(onRejected)
        })
      } else {
        this.PromiseCallbacks.push({
          onResolved() {
            callback(onResolved)
          },
          onRejected() {
            callback(onRejected)
          }
        })
      }
    })
  }

  catch (onRejected) {
    return this.then(undefined, onRejected)
  }

  static resolve(value) {
    return new MyPromise((resolve, reject) => {
      if (value instanceof MyPromise) {
        value.then(v => {
          resolve(v)
        }, r => {
          reject(r)
        })
      } else {
        resolve(value)
      }
    })
  }

  static reject(reason) {
    return new MyPromise((undefined, reject) => {
      reject(reason)
    })
  }

  static all(promises) {
    return new MyPromise((resolve, reject) => {
      let promiseCount = 0 // 记录成功的个数
      let promiseResults = [] // 记录成功的promise值
      promises.forEach((promise, index) => {
        promise.then(value => {
          promiseResults[index] = value
          if (++promiseCount === promises.length) resolve(promiseResults)
        }, reason => {
          reject(reason)
        })
      })
    })
  }

  static race(promises) {
    return new MyPromise((resolve, reject) => {
      promises.forEach(promise => {
        promise.then(value => {
          resolve(value)
        }, reason => {
          reject(reason)
        })
      })
    })
  }
}